<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加标签"
    width="800px"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="edit-tag-container">
      <!-- 已选标签区域 -->
      <div class="selected-tags-section">
        <div class="section-title">
          <span>用户标签：</span>
        </div>
        <div class="selected-tags-list">
          <el-tag
            v-for="tag in selectedTags"
            :key="tag.id"
            :color="tag.color"
            style="color: #ffffff; border: none; font-weight: 500; margin-right: 8px; margin-bottom: 8px;"
            closable
            @close="removeSelectedTag(tag.id)"
            class="selected-tag-item"
          >
            {{ tag.name }}
          </el-tag>
          <div v-if="selectedTags.length === 0" class="empty-tip">
            暂无标签
          </div>
        </div>
      </div>

      <!-- 标签选择区域 -->
      <div class="tag-selection-section">
        <el-container class="tag-selection-container">
          <!-- 左侧分类菜单 -->
          <el-aside width="160px" class="category-aside">
            <el-menu
              :default-active="activeCategory?.id?.toString()"
              class="category-menu"
              mode="vertical"
              @select="handleMenuSelect"
            >
              <el-menu-item
                v-for="category in categories"
                :key="category.id"
                :index="category.id.toString()"
              >
                {{ category.name }}
              </el-menu-item>
            </el-menu>
          </el-aside>

          <!-- 右侧标签内容区 -->
          <el-main class="tag-main-content">
            <div v-if="activeCategory" class="content-container">
              <!-- 分类标题和搜索 -->
              <div class="content-header">
                <h3 class="category-title">{{ activeCategory.name }}</h3>
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索标签"
                  clearable
                  style="width: 200px;"
                >
                  <template #prefix>
                    <Icon icon="ep:search" />
                  </template>
                </el-input>
              </div>

              <!-- 二级分类和标签 -->
              <div 
                v-for="subCategory in currentSubCategories" 
                :key="subCategory.id"
                class="sub-category-section"
              >
                <!-- 二级分类标题 -->
                <el-divider content-position="left">
                  <span style="color: #606266; font-size: 14px;">{{ subCategory.name }}</span>
                </el-divider>

                                 <!-- 该二级分类下的标签 -->
                 <div class="tags-grid">
                   <el-tag
                     v-for="tag in getTagsBySubCategory(subCategory.id)"
                     :key="tag.id"
                     :color="tag.color"
                     :class="['selectable-tag', { selected: isTagSelected(tag.id) }]"
                     style="color: #ffffff; border: none; font-weight: 500; margin: 4px; transition: all 0.2s ease;"
                     @click="toggleTag(tag)"
                   >
                     {{ tag.name }}
                   </el-tag>
                 </div>
              </div>
            </div>
            <div v-else class="empty-content">
              <el-empty description="请选择一个分类" />
            </div>
          </el-main>
        </el-container>
      </div>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
interface UserTag {
  id: number
  name: string
  color: string
  categoryId: number
  subCategoryId: number
  categoryName: string
  subCategoryName: string
}

interface TagCategory {
  id: number
  name: string
}

interface TagSubCategory {
  id: number
  name: string
  categoryId: number
}

const props = defineProps<{
  userId: number
  currentTags: UserTag[]
}>()

const emit = defineEmits<{
  success: [tags: UserTag[]]
}>()

const message = useMessage()

const dialogVisible = ref(false)
const activeCategory = ref<TagCategory>()
const selectedTags = ref<UserTag[]>([])
const searchKeyword = ref('')

// 模拟分类数据
const categories = ref<TagCategory[]>([
  { id: 1, name: '体质' },
  { id: 2, name: '疾病' },
  { id: 3, name: '症状' },
  { id: 4, name: '生活习惯' },
  { id: 5, name: '饮食偏好' }
])

// 模拟二级分类数据
const subCategories = ref<TagSubCategory[]>([
  // 体质二级分类
  { id: 1, name: '虚证体质', categoryId: 1 },
  { id: 2, name: '实证体质', categoryId: 1 },
  { id: 3, name: '平和体质', categoryId: 1 },
  
  // 疾病二级分类
  { id: 4, name: '慢性疾病', categoryId: 2 },
  { id: 5, name: '急性疾病', categoryId: 2 },
  { id: 6, name: '功能性疾病', categoryId: 2 },
  
  // 症状二级分类
  { id: 7, name: '神经系统症状', categoryId: 3 },
  { id: 8, name: '消化系统症状', categoryId: 3 },
  { id: 9, name: '循环系统症状', categoryId: 3 },
  
  // 生活习惯二级分类
  { id: 10, name: '作息习惯', categoryId: 4 },
  { id: 11, name: '运动习惯', categoryId: 4 },
  { id: 12, name: '不良嗜好', categoryId: 4 },
  
  // 饮食偏好二级分类
  { id: 13, name: '口味偏好', categoryId: 5 },
  { id: 14, name: '食物偏好', categoryId: 5 },
  { id: 15, name: '饮食习惯', categoryId: 5 }
])

// 模拟标签数据
const allTags = ref<UserTag[]>([
  // 体质分类 - 虚证体质
  { id: 1, name: '阳虚体质', color: '#FF6B6B', categoryId: 1, subCategoryId: 1, categoryName: '体质', subCategoryName: '虚证体质' },
  { id: 2, name: '阴虚体质', color: '#4ECDC4', categoryId: 1, subCategoryId: 1, categoryName: '体质', subCategoryName: '虚证体质' },
  { id: 3, name: '气虚体质', color: '#45B7D1', categoryId: 1, subCategoryId: 1, categoryName: '体质', subCategoryName: '虚证体质' },
  // 体质分类 - 实证体质
  { id: 4, name: '痰湿体质', color: '#F7DC6F', categoryId: 1, subCategoryId: 2, categoryName: '体质', subCategoryName: '实证体质' },
  { id: 5, name: '湿热体质', color: '#BB8FCE', categoryId: 1, subCategoryId: 2, categoryName: '体质', subCategoryName: '实证体质' },
  { id: 6, name: '血瘀体质', color: '#85C1E9', categoryId: 1, subCategoryId: 2, categoryName: '体质', subCategoryName: '实证体质' },
  // 体质分类 - 平和体质
  { id: 7, name: '平和体质', color: '#82E0AA', categoryId: 1, subCategoryId: 3, categoryName: '体质', subCategoryName: '平和体质' },
  { id: 8, name: '气郁体质', color: '#F8C471', categoryId: 1, subCategoryId: 3, categoryName: '体质', subCategoryName: '平和体质' },
  
  // 疾病分类 - 慢性疾病
  { id: 9, name: '糖尿病', color: '#E74C3C', categoryId: 2, subCategoryId: 4, categoryName: '疾病', subCategoryName: '慢性疾病' },
  { id: 10, name: '高血压', color: '#9B59B6', categoryId: 2, subCategoryId: 4, categoryName: '疾病', subCategoryName: '慢性疾病' },
  { id: 11, name: '冠心病', color: '#3498DB', categoryId: 2, subCategoryId: 4, categoryName: '疾病', subCategoryName: '慢性疾病' },
  // 疾病分类 - 急性疾病
  { id: 12, name: '急性胃炎', color: '#1ABC9C', categoryId: 2, subCategoryId: 5, categoryName: '疾病', subCategoryName: '急性疾病' },
  { id: 13, name: '急性咽炎', color: '#F39C12', categoryId: 2, subCategoryId: 5, categoryName: '疾病', subCategoryName: '急性疾病' },
  // 疾病分类 - 功能性疾病
  { id: 14, name: '失眠症', color: '#8E44AD', categoryId: 2, subCategoryId: 6, categoryName: '疾病', subCategoryName: '功能性疾病' },
  { id: 15, name: '焦虑症', color: '#27AE60', categoryId: 2, subCategoryId: 6, categoryName: '疾病', subCategoryName: '功能性疾病' },
  
  // 症状分类 - 神经系统症状
  { id: 16, name: '头痛', color: '#FF5722', categoryId: 3, subCategoryId: 7, categoryName: '症状', subCategoryName: '神经系统症状' },
  { id: 17, name: '眩晕', color: '#9C27B0', categoryId: 3, subCategoryId: 7, categoryName: '症状', subCategoryName: '神经系统症状' },
  { id: 18, name: '失眠', color: '#673AB7', categoryId: 3, subCategoryId: 7, categoryName: '症状', subCategoryName: '神经系统症状' },
  // 症状分类 - 消化系统症状
  { id: 19, name: '腹痛', color: '#3F51B5', categoryId: 3, subCategoryId: 8, categoryName: '症状', subCategoryName: '消化系统症状' },
  { id: 20, name: '便秘', color: '#2196F3', categoryId: 3, subCategoryId: 8, categoryName: '症状', subCategoryName: '消化系统症状' },
  // 症状分类 - 循环系统症状
  { id: 21, name: '心悸', color: '#03DAC6', categoryId: 3, subCategoryId: 9, categoryName: '症状', subCategoryName: '循环系统症状' },
  { id: 22, name: '胸闷', color: '#4CAF50', categoryId: 3, subCategoryId: 9, categoryName: '症状', subCategoryName: '循环系统症状' },
  
  // 生活习惯分类 - 作息习惯
  { id: 23, name: '熬夜', color: '#795548', categoryId: 4, subCategoryId: 10, categoryName: '生活习惯', subCategoryName: '作息习惯' },
  { id: 24, name: '作息不规律', color: '#607D8B', categoryId: 4, subCategoryId: 10, categoryName: '生活习惯', subCategoryName: '作息习惯' },
  // 生活习惯分类 - 运动习惯
  { id: 25, name: '久坐', color: '#424242', categoryId: 4, subCategoryId: 11, categoryName: '生活习惯', subCategoryName: '运动习惯' },
  { id: 26, name: '运动不足', color: '#8BC34A', categoryId: 4, subCategoryId: 11, categoryName: '生活习惯', subCategoryName: '运动习惯' },
  // 生活习惯分类 - 不良嗜好
  { id: 27, name: '吸烟', color: '#CDDC39', categoryId: 4, subCategoryId: 12, categoryName: '生活习惯', subCategoryName: '不良嗜好' },
  { id: 28, name: '饮酒', color: '#FFC107', categoryId: 4, subCategoryId: 12, categoryName: '生活习惯', subCategoryName: '不良嗜好' },
  
  // 饮食偏好分类 - 口味偏好
  { id: 29, name: '嗜甜', color: '#FF69B4', categoryId: 5, subCategoryId: 13, categoryName: '饮食偏好', subCategoryName: '口味偏好' },
  { id: 30, name: '重口味', color: '#DC143C', categoryId: 5, subCategoryId: 13, categoryName: '饮食偏好', subCategoryName: '口味偏好' },
  // 饮食偏好分类 - 食物偏好
  { id: 31, name: '肉食为主', color: '#4169E1', categoryId: 5, subCategoryId: 14, categoryName: '饮食偏好', subCategoryName: '食物偏好' },
  { id: 32, name: '素食为主', color: '#FF4500', categoryId: 5, subCategoryId: 14, categoryName: '饮食偏好', subCategoryName: '食物偏好' },
  // 饮食偏好分类 - 饮食习惯
  { id: 33, name: '偏寒凉', color: '#8B4513', categoryId: 5, subCategoryId: 15, categoryName: '饮食偏好', subCategoryName: '饮食习惯' },
  { id: 34, name: '偏温热', color: '#32CD32', categoryId: 5, subCategoryId: 15, categoryName: '饮食偏好', subCategoryName: '饮食习惯' }
])

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  selectedTags.value = [...props.currentTags]
  // 默认选择第一个分类
  if (categories.value.length > 0) {
    selectCategory(categories.value[0])
  }
}

/** 选择分类 */
const selectCategory = (category: TagCategory) => {
  activeCategory.value = category
  searchKeyword.value = '' // 清空搜索
}

/** 菜单选择处理 */
const handleMenuSelect = (index: string) => {
  const categoryId = parseInt(index)
  const category = categories.value.find(c => c.id === categoryId)
  if (category) {
    selectCategory(category)
  }
}

/** 获取当前一级分类下的二级分类 */
const currentSubCategories = computed(() => {
  if (!activeCategory.value) return []
  return subCategories.value.filter(sub => sub.categoryId === activeCategory.value!.id)
})

/** 根据二级分类ID获取标签 */
const getTagsBySubCategory = (subCategoryId: number) => {
  let tags = allTags.value.filter(tag => tag.subCategoryId === subCategoryId)
  
  // 搜索过滤
  if (searchKeyword.value) {
    tags = tags.filter(tag => 
      tag.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  return tags
}

/** 检查标签是否已选择 */
const isTagSelected = (tagId: number) => {
  return selectedTags.value.some(tag => tag.id === tagId)
}

/** 切换标签选择状态 */
const toggleTag = (tag: UserTag) => {
  const index = selectedTags.value.findIndex(t => t.id === tag.id)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
}

/** 移除已选标签 */
const removeSelectedTag = (tagId: number) => {
  const index = selectedTags.value.findIndex(tag => tag.id === tagId)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  }
}

/** 确认提交 */
const handleConfirm = async () => {
  try {
    // TODO: 调用API保存用户标签
    // await UserTagApi.updateUserTags(props.userId, selectedTags.value.map(t => t.id))
    
    emit('success', selectedTags.value)
    dialogVisible.value = false
  } catch (error) {
    message.error('保存失败，请重试')
  }
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.edit-tag-container {
  .selected-tags-section {
    margin-bottom: 20px;
    
    .section-title {
      margin-bottom: 12px;
      font-weight: 500;
      color: #303133;
    }
    
    .selected-tags-list {
      min-height: 40px;
      padding: 8px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #fafafa;
      
      .empty-tip {
        color: #909399;
        font-size: 14px;
        line-height: 24px;
      }
      
      .selected-tag-item {
        :deep(.el-tag__close) {
          color: #ffffff !important;
          
          &:hover {
            color: #ffffff !important;
            background-color: rgba(255, 255, 255, 0.2) !important;
          }
        }
      }
    }
  }
  
  .tag-selection-section {
    .tag-selection-container {
      border: 1px solid var(--el-border-color);
      border-radius: var(--el-border-radius-base);
      overflow: hidden;
      height: 500px;
      
      .category-aside {
        border-right: 1px solid var(--el-border-color);
        
        .category-menu {
          border-right: none;
          height: 100%;
          
          :deep(.el-menu-item) {
            height: auto;
            padding: 16px 20px;
            line-height: 1.5;
          }
        }
      }
      
      .tag-main-content {
        padding: 0;
        
        .content-container {
          padding: 20px;
          height: 500px;
          overflow-y: auto;
          
          .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            
            .category-title {
              margin: 0;
              font-size: 18px;
              font-weight: 600;
              color: var(--el-text-color-primary);
            }
          }
          
          .sub-category-section {
            margin-bottom: 24px;
            
            &:last-child {
              margin-bottom: 0;
            }
          }
          
          .tags-grid {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 16px;
            
            .selectable-tag {
              cursor: pointer;
              position: relative;
              
              &.selected {
                &::after {
                  content: '✓';
                  position: absolute;
                  top: -8px;
                  right: -8px;
                  width: 16px;
                  height: 16px;
                  background-color: var(--el-color-primary);
                  color: white;
                  border-radius: 50%;
                  font-size: 10px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-weight: bold;
                }
              }
                         }
           }
         }
         
         .empty-content {
           display: flex;
           align-items: center;
           justify-content: center;
           height: 500px;
         }
       }
     }
  }
}
</style> 
